// VS_BEGIN
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec2 aCoord;

out vec2 g_coord;

void main() {
    gl_Position = vec4(aPos, 1.0f);
    g_coord = aCoord;
}
// VS_END

// FS_BEGIN
#version 330 core
// layout (location = 0) out vec3 shadowMap;

in vec2 g_coord;


uniform sampler2D u_lightViewObjectIDMap;
uniform sampler2D u_objectIDMap;
uniform sampler2D u_positionRT;
uniform sampler2D u_normalRT;
uniform sampler2D u_lightDepthMap;
uniform mat4 u_lightPV;
uniform float u_zNear;
uniform float u_zFar;
uniform vec3 u_camPos;
uniform vec3 u_camFront;
uniform vec3 u_lightDir;

out vec4 FragColor;

void main() {
    // 剔除背景
    vec3 position = texture(u_positionRT, g_coord).xyz;
    if (position == vec3(0.0f)) {
        FragColor = vec4(0.0f);
        return;
    }
    vec3 normal = texture(u_normalRT, g_coord).xyz;
    float bias = max(0.05f * (1.0f - dot(normalize(normal), normalize(u_lightDir))), 0.005f);
    vec2 size = 1.0f / textureSize(u_positionRT, 0);
    int blurKernel = 0;  // 3x3
    float sampleNum = 0.0f;
    float sampleR = 0.0f;
    for (int y = -blurKernel; y <= blurKernel; ++y) {
        for (int x = -blurKernel; x <= blurKernel; ++x) {
            position = texture(u_positionRT, g_coord + size * vec2(x, y)).xyz;
            float distanceToCamera = distance(position, u_camPos);
            float frontDisToCamera = distanceToCamera * dot(normalize(position - u_camPos), normalize(u_camFront));
            if (u_zNear < frontDisToCamera && frontDisToCamera < u_zFar) {
                vec4 posOnLight = u_lightPV * vec4(position, 1.0f);
                vec3 norPosOnLight = posOnLight.xyz / posOnLight.w * 0.5f + 0.5f; // [0, 1]
                float depthOnLight = texture(u_lightDepthMap, norPosOnLight.xy).x;
                if (norPosOnLight.z > depthOnLight + bias) {
                    // vec4 id = texture(u_objectIDMap, g_coord + size * vec2(x, y));
                    // vec4 lightViewID = texture(u_lightViewObjectIDMap, norPosOnLight.xy);
                    // if (id != lightViewID) {
                        sampleR += 1.0f;    
                    // }
                }
            }
            sampleNum += 1.0f;
        }
    }
    FragColor = vec4(vec3(0.0f), sampleR / sampleNum * 0.7f);
}

// FS_END